package message_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/utils"
	"time"

	"github.com/gin-gonic/gin"
)

type UserListResponse struct {
	SendUserID       uint      `json:"send_user_id"` // 发送人
	SendUserNickName string    `json:"send_user_nick_name"`
	SendUserAvatar   string    `json:"send_user_avatar"`
	RevUserID        uint      `json:"rev_user_id"` // 接收人
	RevUserNickName  string    `json:"rev_user_nick_name"`
	RevUserAvatar    string    `json:"rev_user_avatar"`
	Content          string    `json:"content"`       // 内容
	CreatedAt        time.Time `json:"created_at"`    // 消息最新时间
	MessageCount     int       `json:"message_count"` // 消息未读数
}

type MessageGroup map[uint]*UserListResponse

func (MessageApi) MessageListUserView(c *gin.Context) {
	claims, _ := c.Get("user")
	user := claims.(*utils.UserClaims)

	messageList := make([]*models.MessageModel, 0)
	err := common.DB.Order("created_at ASC").Find(&messageList, "send_user_id = ? OR rev_user_id = ?", user.UserID, user.UserID).Error
	if err != nil {
		common.Log.Error(err.Error())
		http.FailWithMessage("聊天记录查询失败", c)
		return
	}

	var messageGroup = MessageGroup{}
	var userLists []UserListResponse
	for _, model := range messageList {
		// 判断是一个组的条件
		// send_user_id 和 rev_user_id 其中一个
		// 1 2  2 1
		// 1 3  3 1
		userList := UserListResponse{
			SendUserID:       model.SendUserID,
			SendUserNickName: model.SendUserNickName,
			SendUserAvatar:   model.SendUserAvatar,
			RevUserID:        model.RevUserID,
			RevUserNickName:  model.RevUserNickName,
			RevUserAvatar:    model.RevUserAvatar,
			Content:          model.Content,
			CreatedAt:        model.CreatedAt,
			MessageCount:     1,
		}
		idNum := model.SendUserID + model.RevUserID
		val, ok := messageGroup[idNum]
		if !ok {
			// 不存在
			messageGroup[idNum] = &userList
			continue
		}
		userList.MessageCount = val.MessageCount + 1
		messageGroup[idNum] = &userList
	}
	for _, message := range messageGroup {
		userLists = append(userLists, *message)
	}

	http.IsOkWithData(userLists, c)
}
